package com.lj.luoye.lotteryticket.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.lj.luoye.lotteryticket.entity.MyBase;

import java.util.List;

public abstract class BaseDao<T extends MyBase> {

    public DBHelper dbHelper;
    public Context context;

    public BaseDao(Context context) {
        this.dbHelper = new DBHelper(context);
        this.context = context;
    }

    public int insertOrUpdate(T t) {
        if (t.getId() > 0){
            return update(t);
        }else {
            return insert(t);
        }
    }

    public int insert(T t){
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues contentValues = t.getContentValues();
        long id = db.insert(t.getTableName(), null, contentValues);
        db.close();
        return (int) id;
    }

    public int update(T t) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        ContentValues contentValues = t.getContentValues();
        int res = db.update(t.getTableName(), contentValues, "id=?", new String[]{t.getId()+""});
        db.close();
        return res;
    }

    public long remove(T t) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        long res = db.delete(t.getTableName(), "id=?", new String[]{t.getId() + ""});
        db.close();
        return res;
    }

    public int clear(T t) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        long num = db.delete(t.getTableName(), null, null);
        db.close();
        return (int) num;
    }

    public abstract T getById(int id);

    public abstract List<T> getAll();

    public abstract List<T> getByCondition(String key, String value);

}
